<?php
namespace Api\Controller;
use Think\Controller;
use Think\Vender;
class SpendController extends BaseController{
	//此处的appid为诗宇公众号
	const RPURL='https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
	const APPID='wx0b27ff95a3a3c401';
	const SECRET='bb107f7d5b7cd188a2e2682468e104d3';
	const MCH_ID='1490328182';
	const KEY='EaAlMyhV1hPkE433zAOLQkfRbgjPVFwz';	
	private $params;
	public function __construct(){
		parent::__construct();
		$this->params=[
			
		    'nonce_str'		=> md5(time()), //随机字符串
            'mch_billno'	=> time(),//商户订单号
            'mch_id'		=> self::MCH_ID,//商户号
            'wxappid'		=> self::APPID,//APPid
            'send_name'		=> '诗宇科技测试红包',
            're_openid'		=> 'oWWpO0sEJ67whD7p8khIs1DXjGig',//用户openid
            'total_amount'	=> '100',//付款金额 单位分
            'total_num'		=> 1,//红包发放总人数
            'wishing'		=> '祝你工作顺利!',//红包祝福语
            'client_ip'		=> $_SERVER['SERVER_ADDR'],//IP地址
            'act_name'		=> '开业一周年活动', //活动名称
            'scene_id'      =>'PRODUCT_1',
            'remark'=> '每天都有红包哦!',//备注
		];
	}	

	public function WxRedPack(){
		$res=$this->setSign($this->params);
		$xmldata=$this->arrayToXml($res);
		$returnData=$this->postData(self::RPURL,$xmldata);
		$resdata=$this->xmlToArray($returnData);
		print_r($resdata);
	}

	function postData($url,$xml,$second=30){
	    //初始化curl          
        $ch = curl_init();  
        //设置超时  
        curl_setopt($ch, CURLOP_TIMEOUT, $second);  
        curl_setopt($ch,CURLOPT_URL, $url);  
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);  //不检测服务器安装证书是否正确
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);  
        //设置header  
        curl_setopt($ch, CURLOPT_HEADER, FALSE);  //设置为false
        //要求结果为字符串且输出到屏幕上  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
        //以下是证书相关代码
		  curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		 curl_setopt($ch,CURLOPT_SSLCERT,'./Public/cert/apiclient_cert.pem');
		 curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		  curl_setopt($ch,CURLOPT_SSLKEY,'./Public/cert/apiclient_key.pem');
        //post提交方式  
        curl_setopt($ch, CURLOPT_POST, TRUE);  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);  
        //运行curl  
        $data = curl_exec($ch);  
        curl_close($ch);  
        //返回结果  
        if($data){  
            curl_close($ch);  
            return $data;  
        }  
        else{   
            $error = curl_error($ch);  
            echo "curl出错，错误码:".var_dump(curl_error($ch))."<br>";     
            curl_close($ch);  
            return false;  
        }  
	}
}